const express = require("express")
const app = express()

const jwt = require("jsonwebtoken")

const ARRSTU = [
    {
        id: "1",
        name: "孙悟空",
        age: "18",
        gender: "男",
        address: "花果山"
    }, {
        id: "2",
        name: "猪八戒",
        age: "28",
        gender: "男",
        address: "高老庄"
    }, {
        id: "3",
        name: "沙和尚",
        age: "38",
        gender: "男",
        address: "流沙河"
    },

]

app.use(express.urlencoded({ extended: true }))
// 解析json格式请求体的中间件
app.use(express.json())

app.use((req, res, next) => {
    // 设置响应头
    res.setHeader("Access-Control-Allow-Origin", "*")
    res.setHeader("Access-Control-Allow-Method", "GET,POST,PUT,DELETE,PATCH")
    res.setHeader("Access-Control-Allow-Headers", "Content-type,authorization")
    // Access-Control-Allow-Origin设定值只能设置一个
    // res.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:5500")允许的请求方式
    // Access-Control-Allow-method 允许的请求方式
    // Access-Control-Allow-Headers 允许传递的请求头
    next()
})

//设置一个登录的路由
app.post("/login", (req, res) => {
    // 输入用户和密码
    const { username, password } = req.body
    // 验证用户名和密码
    if (username === "admin" && password === "123") {
        //登陆成功生成token
        const token = jwt.sign({
            id: "12345", username: "admin", nickname: "超级管理员"
        }, "mima", {
            expiresIn: "1d"
        })

        // 登陆成功
        res.send({
            status: "ok",
            data: {
                token,
                nickname: "超级管理员"
            }
        })
    } else {
        res.status(403).send({
            status: "err",
            data: "用户名密码错误"
        })
    }
})

app.get("/text",(req,res) => {
    
})

// 定义一个学生的路由
app.get("/students", (req, res) => {
    //对token进行解码
    try {
        // 这个路由必须在用户登录后才能访问
        // 需要检查用户是否登录
        const token = req.get("authorization").split(" ")[1]
        const decodeToken = jwt.verify(token, "mima")
        // 解码成功，token有效
    } catch {
        // 解码错误，token无效
        res.status(403).send({
            status: "err",
            data: "token无效"
        })
    }

    res.send({
        status: "ok",
        data: ARRSTU
    })

})

// 定义一个添加学生的路由
app.post("/students", (req, res) => {
    //获取学生的信息
    const { name, age, gender, address } = req.body

    const stu = {
        id: +ARRSTU.at(-1).id + 1 + "",
        name,
        age,
        gender,
        address
    }
    ARRSTU.push(stu)

    res.send({
        status: "ok",
        result: stu
    })

})

// 查询某个学生的路由
app.get("/students/:id", (req, res) => {
    const id = req.params.id
    const user = ARRSTU.find(item => item.id === id)

    if (user) {
        res.send({
            status: "ok",
            data: user
        })
    } else {
        res.send({
            status: "403"
        })
    }
})

// 定义一个删除学生的路由
app.delete("/students/:id", (req, res) => {
    const id = req.params.id

    for (let i = 0; i < ARRSTU.length; i++) {
        if (ARRSTU[i].id === id) {
            const deluser = ARRSTU[i]
            ARRSTU.splice(i, 1)
            res.send({
                status: "ok",
                data: deluser
            })
            return
        }
    }

    res.status(403).send({
        status: "error",
        date: "没有这个id"
    })
})

// 定义一个修改学生的路由
app.put("/students", (req, res) => {
    const { id, name, age, gender, address } = req.body
    const revise = ARRSTU.find(item => item.id === id)

    if (revise) {
        revise.id = id
        revise.name = name
        revise.age = age
        revise.gender = gender
        revise.address = address

        res.send({
            status: "ok",
            date: revise
        })
    } else {
        res.status(403).send({
            status: "error",
            date: "没有这个id"
        })
    }
})

app.listen(3000, () => {
    console.log("服务器已开启");
})